package cn.iocoder.an.module.business.service.equipmenttype;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.framework.common.enums.CommonStatusEnum;
import cn.iocoder.an.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.an.module.business.controller.admin.equipmentmanage.vo.ImportRespVO;
import cn.iocoder.an.module.business.dal.dataobject.equipmentkeeptype.EquipmentKeepTypeDO;
import cn.iocoder.an.module.business.dal.dataobject.equipmentmanage.EquipmentManageDO;
import cn.iocoder.an.module.system.dal.dataobject.dept.DeptDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import cn.iocoder.an.module.business.controller.admin.equipmenttype.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.equipmenttype.EquipmentTypeDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.equipmenttype.EquipmentTypeMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;
import static cn.iocoder.an.module.system.enums.ErrorCodeConstants.DEPT_NOT_FOUND;

/**
 * 设备分类 Service 实现类
 *
 * @author zzy
 */
@Service
@Validated
public class EquipmentTypeServiceImpl implements EquipmentTypeService {

    @Resource
    private EquipmentTypeMapper equipmentTypeMapper;

    @Override
    public Long createEquipmentType(EquipmentTypeSaveReqVO createReqVO) {
        // 插入
        // 校验分类名称 不能重复
        checkRepeatName(createReqVO);
        LambdaQueryWrapper<EquipmentTypeDO> queryWrapper = new LambdaQueryWrapper<>();
        EquipmentTypeDO equipmentType = BeanUtils.toBean(createReqVO, EquipmentTypeDO.class);
        equipmentTypeMapper.insert(equipmentType);
        // 返回
        return equipmentType.getId();
    }

    @Override
    public void updateEquipmentType(EquipmentTypeSaveReqVO updateReqVO) {
        // 校验存在
        validateEquipmentTypeExists(updateReqVO.getId());
        checkRepeatName(updateReqVO);
        // 更新
        EquipmentTypeDO updateObj = BeanUtils.toBean(updateReqVO, EquipmentTypeDO.class);
        equipmentTypeMapper.updateById(updateObj);
    }

    @Override
    public void deleteEquipmentType(Long id) {
        // 校验存在
        validateEquipmentTypeExists(id);
        // 删除
        equipmentTypeMapper.deleteById(id);
    }

    @Override
        public void deleteEquipmentTypeListByIds(List<Long> ids) {
        // 删除
        equipmentTypeMapper.deleteByIds(ids);
        }


    private void validateEquipmentTypeExists(Long id) {
        if (equipmentTypeMapper.selectById(id) == null) {
            throw exception(EQUIPMENT_TYPE_NOT_EXISTS);
        }
    }

    @Override
    public EquipmentTypeDO getEquipmentType(Long id) {
        return equipmentTypeMapper.selectById(id);
    }

    @Override
    public List<EquipmentTypeDO> getEquipmentTypeList() {
        return equipmentTypeMapper.selectList();
    }

    @Override
    public PageResult<EquipmentTypeDO> getEquipmentTypePage(EquipmentTypePageReqVO pageReqVO) {
        return equipmentTypeMapper.selectPage(pageReqVO);
    }

    @Override
    public Long getEquipmentTypeIdByName(String equipmentClassifyName) {
        EquipmentTypeDO typeDO = equipmentTypeMapper.selectFirstOne(
                EquipmentTypeDO::getName, equipmentClassifyName
        );
        if (typeDO != null) {
            return typeDO.getId();
        }else {
            throw exception(EQUIPMENT_TYPE_NOT_EXISTS);
        }
    }

    @Override
    public ImportRespVO importList(List<EquipmentTypeImportExcelVO> list, boolean isUpdateSupport) {
        // 1.1 参数校验
        if (CollUtil.isEmpty(list)) {
            throw exception(IMPORT_EQUIPMENT_MANAGE_NOT_EXISTS);
        }


        //2.记录成功或失败记录
        ImportRespVO respVO = ImportRespVO.builder().insertNameList(new ArrayList<>())
                .updateNameList(new ArrayList<>()).failureMap(new LinkedHashMap<>()).build();

        AtomicInteger count = new AtomicInteger(1);
        list.forEach(equipment -> {
            count.incrementAndGet();//记录行号

            // 2.1.2 校验名称
            if (StringUtils.isEmpty(equipment.getName())) {
                respVO.getFailureMap().put("第" + count + "行数据", "分类名称不能为空!");
                return;
            }


            equipmentTypeMapper.insert(BeanUtils.toBean(equipment, EquipmentTypeDO.class));
            respVO.getInsertNameList().add(equipment.getName());
        });
        return respVO;
    }

    public void checkRepeatName(EquipmentTypeSaveReqVO saveReqVO) {
        LambdaQueryWrapperX<EquipmentTypeDO> queryWrapper = new LambdaQueryWrapperX<>();
        String name = saveReqVO.getName();
        queryWrapper.eq(EquipmentTypeDO::getName, name);
        if (saveReqVO.getId() == null) {
            //1.新增  检查是否已经存在相同名称的分类
            if (equipmentTypeMapper.exists(queryWrapper)) {
                throw exception(EQUIPMENT_TYPE_ALREADY_EXISTS);
            }
        } else {
            //如果是修改操作 排除自身
            queryWrapper.ne(EquipmentTypeDO::getId, saveReqVO.getId());
            if (equipmentTypeMapper.exists(queryWrapper)) {
                throw exception(EQUIPMENT_TYPE_ALREADY_EXISTS);
            }
        }
    }

}